﻿CREATE PROCEDURE USP_GetArgument
	@NodeId int,
	@UserId int,
	@Depth int
AS 

	SET NOCOUNT ON;

	declare @Nodes table (
		id int
	)

	declare @Edges table (
		id int,
		parent int,
		child int
	)

	declare @OpenEdges table (
		id int,
		parent int,
		child int
	)

	declare @OpenNodes table (
		id int
	)

	-- Start it off
	insert into @OpenNodes
	select @NodeId

	declare @depthCount int = 0;

	while (@depthCount <= @Depth or @Depth is null or @Depth < 0) and exists(select 1 from @OpenNodes)
	begin
		insert into @OpenEdges
		select id, parent_id, child_id
		from NodeLinks
		where parent_id in (select id from @OpenNodes)

		insert into @Nodes
		select * from @OpenNodes

		delete from @OpenNodes

		insert into @OpenNodes
		select distinct child from @OpenEdges
		where child not in (select id from @Nodes)

		insert into @Edges
		select * from @OpenEdges

		delete from @OpenEdges

		set @depthCount = @depthCount + 1
	end

	
	select distinct Nodes.Id, Nodes.Title, Nodes.Published, Nodes.[Type], Nodes.AddedBy_UserId, NodeVotes.Agreement, NodeVotes.Logic
	from Nodes
	inner join @Nodes as N on N.id = Nodes.Id
	left join NodeVotes on Nodes.Id = NodeVotes.Node_Id and NodeVotes.Author_UserId = @UserId

	select distinct id, parent, child
	from @Edges